package com.app.bimo.commonbusiness.network;


import android.util.Log;

import com.alibaba.android.arouter.BuildConfig;
import com.alibaba.android.arouter.launcher.ARouter;
import com.app.bimo.commonbusiness.util.Constant;
import com.app.bimo.commonbusiness.util.DataUtil;
import com.app.bimo.commonbusiness.util.LoginService;
import com.app.bimo.commonbusiness.util.RouterHub;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.internal.platform.Platform;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.Buffer;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import static okhttp3.internal.platform.Platform.INFO;


class RetrofitUtil{
    private Retrofit mRetrofit;
    private Headers.Builder builder;

    RetrofitUtil(String baseUrl) {
        OkHttpClient okHttpClient;
        builder = new Headers.Builder();
        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);
        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            okHttpClient = new OkHttpClient.Builder()
                    .retryOnConnectionFailure(true)
                    .addInterceptor(this::createHeadRequest)
                    .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                    .hostnameVerifier(new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession session) {
                            return true;
                        }
                    })
                    .connectTimeout(5, TimeUnit.MINUTES)
                    .readTimeout(5, TimeUnit.MINUTES)
                    .callTimeout(5, TimeUnit.MINUTES)
                    .addInterceptor(logging)
                    .build();
        } else {
            okHttpClient = new OkHttpClient.Builder()
                    .retryOnConnectionFailure(true)
                    .addInterceptor(this::createHeadRequest)
                    .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                    .hostnameVerifier(new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession session) {
                            return true;
                        }
                    })
                    .connectTimeout(5, TimeUnit.MINUTES)
                    .readTimeout(5, TimeUnit.MINUTES)
                    .callTimeout(5, TimeUnit.MINUTES)
                    .build();
        }

        mRetrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(okHttpClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(CustomGsonConverterFactory.create())
                .build();
    }


    void addHead(String key, String value) {
        if (builder.get(key) != null) {
            builder.set(key, value);
        } else {
            builder.add(key, value);
        }
    }

    void refreshBuild(String baseUrl) {
        mRetrofit = mRetrofit.newBuilder().baseUrl(baseUrl).build();
    }

    String getHost() {
        return mRetrofit.baseUrl().toString();
    }

    void removeHead(String key) {
        builder.removeAll(key);
    }

    private Response createHeadRequest(Interceptor.Chain chain) throws IOException {
        //如果是登录接口访问  就不生成幽灵用户  以免冲突（两个用户同时生成会导致后面生成的覆盖前面的）
        /*
         * 判断没有登录就执行异步登录
         */
//        if (!((LoginService) ARouter.getInstance().build(RouterHub.ACCOUNT_SERVICE).navigation()).isRealLogin()) {
//            if (DataUtil.isEmpty(builder.get(Constant.HttpToken)) || !((LoginService) ARouter.getInstance().build(RouterHub.ACCOUNT_SERVICE).navigation()).isLogin()) {
//                ((LoginService) ARouter.getInstance().build(RouterHub.ACCOUNT_SERVICE).navigation()).devicesLogin(false);
//            }
//        }
        Request request = chain.request();
        Response response = chain.proceed(request
                .newBuilder()
                .headers(builder.build())
                .build());
        if (BuildConfig.DEBUG)
        {
            if (request.body() != null) {
                Platform.get().log(INFO, getParamContent(request.body()), null);
            }
            Platform.get().log(INFO, "url=" + response.request().url() + "\nheads=" + response.request().headers(), null);
        }

        if (request.body() != null) {
//            Platform.get().log(INFO, "url=" + response.request().url() + "\n" + response.request().headers() + "\n" + getParamContent(request.body()), null);
            Log.i("response","url(POST)=" + response.request().url() + "\n" + response.request().headers() + "\n" + getParamContent(request.body()));
        } else {
//            Platform.get().log(INFO, "url=" + response.request().url(), null);
            Log.i("response","url(GET)=" + response.request().url()+ "\n" + response.request().headers());
        }
//        Log.i("response", "responseResult: " + response.body().string());
        return response;
    }


    public <T> T createService(Class<T> serviceClass) {
        return mRetrofit.create(serviceClass);
    }

    private static String getParamContent(RequestBody body) throws IOException {
        Buffer buffer = new Buffer();
        body.writeTo(buffer);
        return buffer.readUtf8();
    }
}
